//
//  UserDetailController.swift
//  用户详情界面
//
//  Created by smile on 2019/4/14.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//用户详情头部视图
import JXPagingView

//指示器
import JXCategoryView

//自动布局框架
import SnapKit

//导入响应式编程框架
import RxSwift

class UserDetailController: BaseTitleController {
   
    /// 内容布局容器
    @IBOutlet weak var contentContainer: UIView!
    
    var listViewArray:[UIView] = []
    
    /// 用户头部信息View
    var userDetailHeaderView:UserDetailHeaderView!
    
    /// 歌单列表View
    var userDetailSheetView:UserDetailSheetView!
    
    /// 动态列表View
    var userDetailFeedView:UserDetailFeedView!
    
    /// 关于我View
    var userDetailAboutView:UserDetailAboutView!
    
    //下拉刷新View
    //只是我们这里没用到
    var pageView:JXPagingView!
    
    /// 指示器
    //用来显示音乐，动态，关于
    var indicatorView:JXCategoryTitleView!

    /// 用户Id
    var userId:String?
    
    /// 用户昵称
    var nickname:String?
    
    
    override func viewDidLayoutSubviews() {
        //重新设置PageView的尺寸和位置
        pageView.frame = contentContainer.bounds
    }
    
    override func initViews() {
        super.initViews()

        setTitle("用户详情")

        //创建要显示的三个界面
        //创建用户详情View
        userDetailSheetView=UserDetailSheetView()
        userDetailSheetView.onSheetClick={
            data in
            SheetDetailController.start(self.navigationController!, data.id)
        }
        
        userDetailFeedView=UserDetailFeedView()
        
        userDetailAboutView=UserDetailAboutView()
        
        //添加集合
        listViewArray=[userDetailSheetView,userDetailFeedView,userDetailAboutView]

        //创建HeaderView，就是显示用户信息的那部分
        userDetailHeaderView=UserDetailHeaderView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.size.width), height: SIZE_HEADER_HEIGHT))
        
        //关注点击回调方法
        userDetailHeaderView.onFollowClick={
            data in
            self.onFollowClick(data)
        }
        
        //发送消息点击回调方法
        userDetailHeaderView.onSendMessageClick={
            data in
            self.onSendMessageClick(data)
        }

        //创建指示器
        indicatorView=JXCategoryTitleView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.size.width), height: SIZE_INDICATOR_HEIGHT))
 

        //配置指示器
        indicatorView.titles = ["音乐", "动态", "关于"]

        //背景颜色
        indicatorView.backgroundColor = UIColor.white

        indicatorView.delegate = self;

        //选择后的标题颜色
        indicatorView.titleSelectedColor = UIColor(hex: COLOR_PRIMARY)

        //默认颜色
        indicatorView.titleColor = UIColor.black

        indicatorView.titleColorGradientEnabled = true

        //标题选中缩放
        indicatorView.titleLabelZoomEnabled = false

        //选择线
        let lineView = JXCategoryIndicatorLineView.init()

        //颜色
        lineView.indicatorLineViewColor = UIColor(hex: COLOR_PRIMARY)

        //宽度
        lineView.indicatorLineWidth = 60

        indicatorView.indicators = [lineView]

        //下拉刷新View
        //创建PageView
        pageView=JXPagingListRefreshView(delegate: self)
        pageView.mainTableView.gestureDelegate = self

        //添加到布局
        contentContainer.addSubview(pageView)

        //设置指示器
        indicatorView.contentScrollView = pageView.listContainerView.collectionView

        //添加手势识别器
        pageView.listContainerView.collectionView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pageView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
    }
    
    override func initDatas() {
        super.initDatas()
        //先获取用户详情
        if userId != nil {
            //根据Id获取
        
            getUserDetail(self.userId!,nil)
           
        }else if nickname != nil{
            //根据标题
            //获取用户详情
            getUserDetail("-1",nickname!)
        }else{
            //TODO 错误处理
        }
    
    }
    
    /// 关注按钮回调事件方法
    ///
    /// - Parameter data: <#data description#>
    func onFollowClick(_ data:User) {
        if data.isFollowing() {
            //已经关注了
            
            //取消关注
            Api.shared
                .deleteFollow(data.id)
                .subscribeOnSuccess { (_) in
                    //取消关注成功
                    data.following=nil
                    
                    //刷新关注状态
                    self.userDetailHeaderView.showFollowStatus()
                }.disposed(by: disposeBag)
            
        } else {
            Api.shared
                .follow(data.id)
                .subscribeOnSuccess { _ in
                    //关注成功
                    data.following=1
                    
                    //刷新关注状态
                    self.userDetailHeaderView.showFollowStatus()
                }.disposed(by: disposeBag)
            
        }
    }
    
    /// 发送消息按钮点击
    ///
    /// - Parameter data: <#data description#>
    func onSendMessageClick(_ data:User) {
        print("UserDetailController onSendMessageClick:\(data.nickname)")
        ChatController.start(navigationController!, StringUtil.processUserId(data.id))
    }
    
    /// 获取用户详情
    ///
    /// - Parameters:
    ///   - id: <#id description#>
    ///   - nickname: <#nickname description#>
    func getUserDetail(_ id:String!,_ nickname:String?) {
        Api.shared
            .userDetail(id,nickname)
            .subscribeOnSuccess { (data) in
            if let data = data?.data {
                self.showData(data)
            }
        }.disposed(by: disposeBag)
    }
    
    /// 显示用户数据
    ///
    /// - Parameter data: <#data description#>
    func showData(_ data:User) {
        print("user detail show data:\(data.nickname)")
        
        userDetailSheetView.userId=data.id
        userDetailSheetView.customInit()
        
        userDetailFeedView.userId=data.id
        userDetailFeedView.customInit()
        
        userDetailAboutView.userId=data.id
        userDetailAboutView.customInit()
        
        //header
        userDetailHeaderView.bindData(data)
    }
    
    override func initListeners() {
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //必须要这样实现
        //这是指示器规定的
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (indicatorView.selectedIndex == 0)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: - 启动界面
extension UserDetailController{
    /// 通过用户Id启动界面
    ///
    static func start(_ navigationController:UINavigationController,userId:String) {
        //获取Storyboard
        let storyboard=UIStoryboard(name: "Main", bundle: nil)
        
        //创建控制器
        let controller=storyboard.instantiateViewController(withIdentifier: "UserDetail") as! UserDetailController
        
        controller.userId=userId
        
        //将控制器压入导航控制中
        navigationController.pushViewController(controller, animated: true)
        
    }
    
    /// 通过昵称启动界面
    ///
    static func start(_ navigationController:UINavigationController,nickname:String) {
        //创建控制器
        let controller=navigationController.storyboard?.instantiateViewController(withIdentifier: "UserDetail") as! UserDetailController
        
        controller.nickname=nickname
        
        //将控制器压入导航控制中
        navigationController.pushViewController(controller, animated: true)
        
    }
}

// MARK: - PageView代理
extension UserDetailController: JXPagingViewDelegate {
    
    /// 返回头部View高度
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return SIZE_HEADER_HEIGHT
    }
    
    /// 返回头部View
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userDetailHeaderView
    }
    
    /// 指示器高度
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return SIZE_INDICATOR_HEIGHT
    }
    
    /// 指示器View
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return indicatorView
    }
    
    /// 有多少个页面
    ///
    /// - Parameter pagingView: <#pagingView description#>
    /// - Returns: <#return value description#>
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return 3
    }
    
    /// 返回对应位置的View
    ///
    /// - Parameters:
    ///   - pagingView: <#pagingView description#>
    ///   - index: <#index description#>
    /// - Returns: <#return value description#>
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        if index==0 {
            return userDetailSheetView
        }else if index == 1 {
            return userDetailFeedView
        }else {
            return userDetailAboutView
        }
    }
}

// MARK: - 指示器代理
extension UserDetailController: JXCategoryViewDelegate {
    
    /// 点击选中或者滚动选中都会调用该方法
    /// 适用于只关心选中事件
    /// 不关心具体是点击还是滚动选中的
    ///
    /// - Parameters:
    ///   - categoryView: <#categoryView description#>
    ///   - index: <#index description#>
    func categoryView(_ categoryView: JXCategoryBaseView!, didSelectedItemAt index: Int) {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (index == 0)
    }
    
    /// 只有点击选中时调用
    ///
    /// - Parameters:
    ///   - categoryView: <#categoryView description#>
    ///   - index: <#index description#>
    func categoryView(_ categoryView: JXCategoryBaseView!, didClickedItemContentScrollViewTransitionTo index: Int){
        //滚动的到对应的位置
        self.pageView.listContainerView.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false)
        
    }
}

// MARK: - PageMainTableView代理
extension UserDetailController: JXPagingMainTableViewGestureDelegate {
    
    
    /// 主要是处理滑动冲突
    /// 如果headerView（或其他地方）有水平滚动的scrollView
    /// 当其正在左右滑动的时候
    /// 就不能让列表上下滑动
    /// 所以有此代理方法进行对应处理
    ///
    /// - Parameters:
    ///   - gestureRecognizer: <#gestureRecognizer description#>
    ///   - otherGestureRecognizer: <#otherGestureRecognizer description#>
    /// - Returns: <#return value description#>
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {

        //禁止categoryView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == indicatorView?.collectionView.panGestureRecognizer {
            return false
        }
        
        //手势识别器判断
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder())
    }
}
